package com.itheima.reggie.handlerexception;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * 系统异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResultInfo exceptionHandler(Exception e){
        e.printStackTrace();
        return ResultInfo.error("服务器开小差了,稍后重试");
    }

    /**
     * 自定义异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public ResultInfo customException(CustomException e){
        e.printStackTrace();
        return ResultInfo.error(e.getMessage());
    }

    //统一处理字段重复
    @ExceptionHandler(DuplicateKeyException.class)//声明当前方法处理哪种异常
    public ResultInfo duplicateKeyExceptionHandler(DuplicateKeyException e) {
        e.printStackTrace();//打印
        return ResultInfo.error("名称重复");//返回结果
    }
}
